/**
 * Created by macos on 14-10-11.
 */
var  member = require('../api/controllers/MemberController.js');

(function(){
  var ActiveUserClear = {};
  var root = this;

    function findActiveUser(next){

        ActiveUser.find().exec(function (error,result) {
            if(error) {
                sails.log.debug('ActiveUserClear.findActiveUser:', error);
                next({"status":500,"result": 'server error!'});
            }
            next(null, result);
        });
    };

    function destroyActiveUsers(activeUsers, next) {
        sails.log.debug("ActiveUserClear:clear ActiveUser ing ...");
        for(var i in activeUsers) {
            console.log(22222);
            var activeUser = activeUsers[i];

            if (_.has(activeUser, 'updatedAt')) {
                var updatedAt = activeUser.updatedAt.getTime();
                var now = new Date().getTime();
                var diffValue = now - updatedAt;
                var day = diffValue/60000/60/24;
                if(day>3){
                    ActiveUser.destroy( activeUsers[i].id, function userDestroyed(err) {
                        if (err)  sails.log.error("ActiveUser delete failed ! id:"+activeUsers[i].id+"\n");
                    });
                }
            }

        }
    };

    ActiveUserClear.run = function() {

    setInterval(function(){
      async.waterfall([
          findActiveUser,
          destroyActiveUsers
      ], function(error, result){
        if (error) {
          return error;
        }
      });

    }, 86400000);

  }

  module.exports = ActiveUserClear;
})()